<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>绚丽小球</title>
    <style>
        body {
            margin: 150px;
        }

        #canvas {
            box-shadow: 0 0 10px #000;
        }
    </style>
</head>
<body>
<canvas id="canvas">当前浏览器不支持！</canvas>
</body>
<script src="./js/underScore.js"></script>
<script>
    // 1.获取当前的画布
    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');

    canvas.width = 1300;
    canvas.height = 750;

    canvas.style.backgroundColor = '#000';

    // 2. 小球类
    class Ball {

        constructor(x, y, color) {
            this.x = x;
            this.y = y;
            this.color = color;
            this.r = 50;
        }

        /**
         * 绘制小球
         */
        render() {
            ctx.save();
            ctx.beginPath();
            ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2);
            ctx.fillStyle = this.color;
            ctx.fill();
            ctx.restore();
        }
    }

    // let ball = new Ball(50, 50, 'red');
    // ball.render();

    function RandomNumBoth(Min, Max) {
        let Range = Max - Min;
        let Rand = Math.random();
        let num = Min + Math.round(Rand * Range); //四舍五入
        return num;
    }

    // 3. 会移动的小球类
    class MoveBall extends Ball {

        constructor(x, y, color) {
            super(x, y, color);

            // 量的变化
            this.dX = _.random(-5, 5);
            this.dY = _.random(-5, 5);
            this.dR = _.random(0.5, 1);
        }

        upDate() {
            this.x += this.dX;
            this.y += this.dY;
            this.r -= this.dR;
            // 半径小于 0 ，则置空
            if (this.r < 0) {
                this.r = 0;
            }
        }

    }

    // 4. 实例化小球
    let ballAll = [];
    let colorAll = ['red', 'green', 'blue', 'yellow', 'purple', 'pink', 'orange','grey',"#078","#809","#054"];

    // 5. 监听鼠标的移动
    canvas.addEventListener('mousemove', function (e) {
        ballAll.push(new MoveBall(e.offsetX, e.offsetY, colorAll[Math.floor(_.random(0, colorAll.length - 1))]));
        // ballAll.push(new MoveBall(e.offsetX, e.offsetY, colorAll[Math.floor(Math.random()*(colorAll.length-1))]));
        // console.log(ballAll);
    })

    /// 6、开启定时器
    setInterval(function () {
        // 清屏
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        // 绘制
        for (let i = 0; i < ballAll.length; i++) {
            ballAll[i].render();
            ballAll[i].upDate();
        }
    }, 50)
</script>
</html>